package cn.edu.dgut.css.sai.security.oauth2.client.endpoint;

import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;

import java.util.Map;

/**
 * {@link OAuth2AccessTokenResponseClient}委托类
 *
 * @author sai
 * @since 2.2
 */
public final class DelegateSaiOAuth2AccessTokenResponseClient implements OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {

    @Override
    public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
        // 使用 Java 14 switch 表达式
        // Java 14的switch表达式使用箭头表达时，不需要我们在每一个case后都加上break 。
        return switch (authorizationGrantRequest.getClientRegistration().getRegistrationId()) {
            case "qq", "dgut", "weixin", "wxmp" -> new SaiCommonOAuth2AccessTokenResponseClient().getTokenResponse(authorizationGrantRequest);
            case "gitee" -> new SaiGiteeOAuth2AccessTokenResponseClient().getTokenResponse(authorizationGrantRequest);
            case "dingding" ->
                    // 转换为 OAuth2AccessTokenResponse
                    OAuth2AccessTokenResponse
                            .withToken("not_need_token")
                            .tokenType(OAuth2AccessToken.TokenType.BEARER)
                            .additionalParameters(Map.of("code", authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode()))
                            .build();
            default -> new DefaultAuthorizationCodeTokenResponseClient().getTokenResponse(authorizationGrantRequest);
        };
    }
}
